﻿using Admin.NET.Core;
using Admin.NET.Plugin.MQTT.MQTT;
using Admin.NET.Plugin.MQTT.Option;

using Furion;

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;

using MQTTnet;
using MQTTnet.AspNetCore;
using MQTTnet.Server;

namespace Admin.NET.Plugin.MQTT
{
    [AppStartup(100)]
    public class Startup : AppStartup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMqttService();
            services.AddMqttClient();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            var myoption = App.GetConfig<MyMqttServerOptions>("MyMqttServer", true);
         
                app.UseEndpoints(
                   endpoints =>
                   {
                       endpoints.MapConnectionHandler<MqttConnectionHandler>(
                           $"/{myoption.MqttWsPath}",
                           httpConnectionDispatcherOptions => httpConnectionDispatcherOptions.WebSockets.SubProtocolSelector =
                               protocolList => protocolList.FirstOrDefault() ?? string.Empty);
                   });
            var mqttService = App.GetService<MyMqttService>();
            app.UseMqttServer(
                server =>
                {
                    //验证账号密码
                    server.ValidatingConnectionAsync += mqttService.Server_ValidatingConnectionAsync;
                    //侦听为消费消息
                    server.ApplicationMessageNotConsumedAsync += mqttService.Server_ApplicationMessageNotConsumedAsync;
                    //侦听所有消息
                    server.InterceptingPublishAsync += mqttService.Server_InterceptingPublishAsync;
                    //客户端订阅消息
                    server.ClientSubscribedTopicAsync += mqttService.Server_ClientSubscribedTopicAsync;
                    //客户端取消订阅消息
                    server.ClientUnsubscribedTopicAsync += mqttService.Server_ClientUnsubscribedTopicAsync;
                    //客户端链接事件
                    server.ClientConnectedAsync += mqttService.Server_ClientConnectedAsync;
                    //客户端关闭事件
                    server.ClientDisconnectedAsync += mqttService.Server_ClientDisconnectedAsync;
                    //保留消息
                    server.RetainedMessageChangedAsync += mqttService.Server_RetainedMessageChangedAsync;
                });
            
        }
    }
}
